#include "../debug.hpp"
#include "game.hpp"
#include "../glm/glm.hpp"

namespace ps {

PixelShooterGame::PixelShooterGame() : m_window(0),  m_max_players(2)
{
}

void PixelShooterGame::Initialize()
{
	assert(NULL != m_window);

	const char* file = "assets/textures/shps_map_70_65.png";
	if (!m_ship_texture.LoadFromFile(file))
	{
		fire_exception("can't load file %s", file);
	}

	for(int i = 0; i < m_max_players; ++i)
	{
		SpaceShip ship;
		ship.SetWindow(m_window);
		ship.SetImage(m_ship_texture);
		ship.Initialize();
		m_space_ships.push_back(ship);
	}

	#define REGISTER_HANDLER(TCOMMAND, HANDLER)							 \
		m_cmd_connection.RegisterHandler(								 \
			new lge2d::lan::CommandHandler<PixelShooterGame, TCOMMAND>(  \
					this, &HANDLER));

	REGISTER_HANDLER(lan::ErrorCommand, PixelShooterGame::OnErrorCommand);
	REGISTER_HANDLER(lan::VersionCommand, PixelShooterGame::OnVersionCommand);

	#undef REGISTER_HANDLER

	//TODO: remove test connect
	m_cmd_connection.Connect("localhost");
}

void PixelShooterGame::Update(float dt)
{
	m_cmd_connection.Update(dt);

	bool connected = m_cmd_connection.IsConnected();
	if (!connected)
		return;

	for (int i = 0; i < m_max_players; ++i)
	{
		m_space_ships.at(i).Update(dt);
	}

	const sf::Input& input = m_window->GetInput();
	const float STEP = 2.0f;
	if (input.IsKeyDown(sf::Key::W))
	{
		m_space_ships.at(0).MoveTo(0.f, -STEP);
	}
	if (input.IsKeyDown(sf::Key::S))
	{
		m_space_ships.at(0).MoveTo(0.f, STEP);
	}
	if (input.IsKeyDown(sf::Key::D))
	{
		m_space_ships.at(0).MoveTo(STEP, 0.f);
	}
	if (input.IsKeyDown(sf::Key::A))
	{
		m_space_ships.at(0).MoveTo(-STEP, 0.f);
	}
}

void PixelShooterGame::Render() const
{
	bool connected = m_cmd_connection.IsConnected();
	if (!connected)
		return;

	for (int i = 0; i < m_max_players; ++i)
	{
		m_space_ships.at(i).Render();
	}
}

void PixelShooterGame::OnEvent(const sf::Event& event)
{
	bool connected = m_cmd_connection.IsConnected();
	if (!connected)
		return;

	if (event.Type == sf::Event::KeyPressed)
	{
		switch (event.Key.Code)
		{
		case sf::Key::Up:
			m_space_ships.at(0).MoveTo(0.f, -1.f);
			break;
		case sf::Key::Down:
			m_space_ships.at(0).MoveTo(0.f, 1.f);
			break;
		case sf::Key::Left:
			m_space_ships.at(0).MoveTo(-1.f, 0.f);
			break;
		case sf::Key::Right:
			m_space_ships.at(0).MoveTo(1.f, 0.f);
			break;
		default:
			break;
		}
	}
}

void PixelShooterGame::OnVersionCommand(const lan::VersionCommand& cmd)
{

}

void PixelShooterGame::OnErrorCommand(const lan::ErrorCommand& cmd)
{

}

}  // namespace lge2d
